package tests;

public class Keyongyu {

    public static void main(String[] args) {
        int[] ARR = new int[]{-4, 1, 2, 2, 5, 5, 5, 8, 10};
        //使用二分查找， 找到 小于等于 t的最后一个数 ， 假定t = 6.
        int t = 6;
        int index = binarySearch(ARR, t);
        if (index >= 0) {
            System.out.println("result=" + index + ",value=" + ARR[index]);
        } else {
            System.out.println("not found");
        }
    }

    private static int binarySearch(int[] arr, int t) {
        int len = arr.length;
        int low = 0, high = len - 1, mid;

        int find = -1;
        while (low <= high) {
            //取中间
            mid = low + ((high - low) >> 1);
            if (arr[mid] <= t) {//符合条件
                find = mid;
            }
            //继续找
            if (arr[mid] > t) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        //返回最后一次符合条件的位置
        return find;
    }

}